package com.goblin.model.uaa.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.PostConstruct;

import com.goblin.common.util.MessageDigestUtil;
import com.goblin.model.uaa.po.Menu;
import com.goblin.model.uaa.po.Priv;
import com.goblin.model.uaa.po.Role;
import com.goblin.model.uaa.po.User;
import com.goblin.model.uaa.service.MenuService;
import com.goblin.model.uaa.service.PrivService;
import com.goblin.model.uaa.service.RoleService;
import com.goblin.model.uaa.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class InitController {

	@Autowired
	private MenuService menuService;

	@Autowired
	private PrivService privService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private UserService userService;

	private static final Logger logger = LoggerFactory.getLogger(InitController.class);

	@PostConstruct
	public void init() {

		Optional<User> optional = this.userService.findUserByNickName("admin");
		if (optional.isPresent()) {
			return;
		}

		List<Priv> privs = this.privService.all();
		List<Menu> menus = this.menuService.all();

		//创建角色
		Role role = new Role();
		role.setDetail("系统管理员");
		role.setLabel("系统管理员");
		role.setMenus(menus);
		role.setPrivs(privs);
		role = this.roleService.save(role);

		User user = new User();
		user.setMobile("11111111111");
		user.setEmail("11111111111");
		user.setNickName("admin");
		user.setPassword(MessageDigestUtil.base64AndMD5("123456"));
		List<Role> roles = new ArrayList<>();
		roles.add(role);
		user.setRoles(roles);
		this.userService.save(user);

		if (user != null) {
			logger.info("初次启动生成系统管理员用户成功！ 账户： admin 默认密码：123456， 请生成后及时修改");
		}

	}

}
